﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenNETCF.Net;
using System.Diagnostics;

namespace CreateAndDial
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void createAndDial_Click(object sender, EventArgs e)
        {
            CreateEntry(entryName.Text);
            DialEntry(entryName.Text);
        }

        private RasEntry ExistingEntry(string name)
        {
            var existing = Ras.Entries.FirstOrDefault(e => string.Compare(e.Name, name, true) == 0);
            return existing;
        }

        private void CreateEntry(string name)
        {
            var entry = ExistingEntry(name);
            if (entry != null)
            {
                return;
            }
            entry = new RasEntry()
            {
                 Name = name,
                 PhoneNumber = phoneNumber.Text,
                 // TODO: get this from RAS - for this demo/test I know this is the name so I hard-coded it
                 DeviceName = "Hayes Compatible on COM1:",
                 DeviceType = "modem"

            };

            var @params = new RasDialParams()
            {
                UserName = username.Text,
                Password = password.Text,
                Domain = domain.Text
            };

            entry.Options|= (int)(ConnectionOptions.DialAsLocalCall 
                | ConnectionOptions.UseLogonCredentials);

            Ras.CreateEntry(entry, @params);
        }

        private void DialEntry(string name)
        {
            var entry = ExistingEntry(name);
            entry.RasStatus += new RasNotificationHandler(entry_RasStatus);
            entry.Dial(true);
        }

        void entry_RasStatus(int hConn, RasConnState State, RasError ErrorCode)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new EventHandler(delegate
                {
                    entry_RasStatus(hConn, State, ErrorCode);
                }));
                return;
            }

            var msg = string.Format("{0} status: {1}", hConn, State.ToString());
            Debug.WriteLine(msg);
            statusList.Items.Insert(0, msg);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}